package com.vita.bduck.logger;

import android.app.Notification;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import java.util.ArrayList;
import java.util.List;

/**
 * 上传日志去服务器
 */
public class UploadLogService extends Service {
	
	private static final int HANLDE_UPLOAD = 100;
	private static IUploadLog logUpload; 
//	private static IUploadLog operationLogUpload;

	

	
	/**
	 * 每次最大上传的记录数
	 */
	private int maxRow = LogConstant.DEFALUT_MAX_ROW;
	
	/**
	 * 上传间隔时间
	 */
	private int uploadInterval = LogConstant.DEFAULT_UPLOAD_INTERVAL;
	
	private Object lock = new Object();
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
	}

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (intent != null) {
            setForeground();
            mHandler.removeMessages(HANLDE_UPLOAD);
            int oper = intent.getIntExtra(LogConstant.OPERATION, LogConstant.OPERATIONT_STOP);
            if (oper == LogConstant.OPERTAIONT_STAT) {
                maxRow = intent.getIntExtra(LogConstant.MAXROW, LogConstant.DEFALUT_MAX_ROW);
                uploadInterval = intent.getIntExtra(LogConstant.UPLOAD_INTERVAL, LogConstant.DEFAULT_UPLOAD_INTERVAL);
                mHandler.sendEmptyMessage(HANLDE_UPLOAD);
            } else {
                stopSelf();
            }
        }

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		

	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		
		cancleForeground();
		mHandler.removeMessages(HANLDE_UPLOAD);
	}
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case HANLDE_UPLOAD:
				new Thread(new UploadLogRunablue()).start();
				sendEmptyMessageDelayed(HANLDE_UPLOAD, uploadInterval);
				break;
			}
		}
	};
	
	private class UploadLogRunablue implements Runnable {
		
		@Override
		public void run() {
			synchronized (lock) {
				// 先上传日志
				List<LogInfo> logInfoes = new ArrayList<LogInfo>();
				if (logUpload != null) {
					int logCount = LogWritter.getInstance().getLogInfoes(Log.getLogPath(), 
							maxRow, logInfoes);
					if (logCount != 0) {
						boolean result = logUpload.uploadLog(UploadLogService.this, logInfoes);
						// 如果上传成功，则把相应本地Log信息删除
						if (result) {
							LogWritter.getInstance().deleteLog(Log.getLogPath(), logCount);
						}
					}
				}
				
		/*		// 上传操作日志
				List<LogInfo> opLogInfoes = new ArrayList<LogInfo>();
				if (operationLogUpload != null) {
					int logCount = LogWritter.getInstance().getLogInfoes(OperationLog.getOpeationLogPath(), 
							maxRow, opLogInfoes);
					if (logCount != 0) {
						boolean result = operationLogUpload.uploadLog(UploadLogService.this, opLogInfoes);
						// 如果上传成功，则把相应本地Log信息删除
						if (result) {
							LogWritter.getInstance().deleteLog(OperationLog.getOpeationLogPath(), logCount);
						}
					}
				}*/
			}
		}
		
	}
	
	/**
	 * 开始上传日志
	 * @param context
	 * @param logUpload 日志上传实现类
	 * @param operationLogUpload 操作日志上传实现类
	 * @param maxRow 每次上传最大的记录数
	 * @param uploadInterval 上传间隔时间
	 */
	public static void startUploadLog(Context context, IUploadLog logUpload, 
		 int maxRow, int uploadInterval) {
		setLogUpload(logUpload);
		//setOperationLogUpload(operationLogUpload);
		Intent i = new Intent(context, UploadLogService.class);
		i.putExtra(LogConstant.OPERATION, LogConstant.OPERTAIONT_STAT);
		i.putExtra(LogConstant.MAXROW, maxRow);
		i.putExtra(LogConstant.UPLOAD_INTERVAL, uploadInterval);
		context.startService(i);
	}
	
	/**
	 * 停止上传日志
	 * @param context
	 */
	public static void stopUploadLog(Context context) {
		Intent i = new Intent(context, UploadLogService.class);
		i.putExtra(LogConstant.OPERATION, LogConstant.OPERATIONT_STOP);
		context.startService(i);
	}

	public static void setLogUpload(IUploadLog logUpload) {
		UploadLogService.logUpload = logUpload;
	}

/*	public static void setOperationLogUpload(IUploadLog operationLogUpload) {
		UploadLogService.operationLogUpload = operationLogUpload;
	}*/
	
	/**
	 * 用于服务防杀死
	 */
	private void setForeground() {
		Notification note = new Notification(0, null, System.currentTimeMillis());
        note.flags |= Notification.FLAG_NO_CLEAR;
        startForeground(1234567890, note);
	}
	
	/**
	 * 取消服务防杀死
	 */
	private void cancleForeground() {
		stopForeground(true);
	}

}
